package com.hcloud.auth.service;

import com.hcloud.auth.api.user.MyUserDetail;
import com.hcloud.common.core.base.HCloudResult;
import com.hcloud.system.core.bean.user.User;
import com.hcloud.system.api.feign.authority.RemoteAuthorityService;
import com.hcloud.system.api.feign.user.RemoteUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;


/**
 * 查询用户的方法
 */
@Primary
@Service
@Slf4j
@AllArgsConstructor
public class MyUserDetailsService implements UserDetailsService {

    private final RemoteUserService remoteUserService;

    private final RemoteAuthorityService remoteAuthorityService;

    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
//        System.out.println(121212);
//        MyUserDetail user = new MyUserDetail("hepg", new BCryptPasswordEncoder().encode("123456"));
//        user.setId("1234");
//        return user;
        log.info("开始查询用户：{}", account);
        HCloudResult<User> userByAccount = remoteUserService.getUserByAccount(account);
        log.info("用户：{}", userByAccount);
        if (userByAccount != null && userByAccount.getData() != null) {
            MyUserDetail myUserDetail = new MyUserDetail(userByAccount.getData());
            String roles = userByAccount.getData().getRole();
            HCloudResult<List<String>> byRoleIds = remoteAuthorityService.findByRoleIds(roles);
            if (byRoleIds != null && byRoleIds.getData() != null) {
                Set<SimpleGrantedAuthority> set = new HashSet<>();
                for (String datum : byRoleIds.getData()) {
                    if (datum != null && !"".equals(datum)) {
                        SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(datum);
                        set.add(simpleGrantedAuthority);
                    }
                }
                myUserDetail.setAuthorities(set);
            }
            return myUserDetail;
        } else {
            log.error("找不到用户{}", account);
            return null;
        }

    }

    public static void main(String[] args) {
        System.out.println(new BCryptPasswordEncoder().encode("123456"));
    }
}
